<template>
	<div class="app-container">
		<!-- 顶部筛选区域 -->
		<!-- 替换原有的顶部筛选区域 -->
		<el-card>
			<el-form :model="filterForm">
				<el-row :gutter="20">
					<!-- 新增：开始时间 -->
					<el-col :span="5">
						<el-form-item label="开始时间">
							<el-date-picker
								v-model="filterForm.startDate"
								type="date"
								placeholder="选择开始日期"
								value-format="YYYY-MM-DD"
								@change="handleFilterChange"
							/>
						</el-form-item>
					</el-col>

					<!-- 新增：结束时间 -->
					<el-col :span="5">
						<el-form-item label="结束时间">
							<el-date-picker
								v-model="filterForm.endDate"
								type="date"
								placeholder="选择结束日期"
								value-format="YYYY-MM-DD"
								@change="handleFilterChange"
							/>
						</el-form-item>
					</el-col>

					<!-- 新增：成本类别 -->
					<el-col :span="5">
						<el-form-item label="成本类别">
							<el-select
								v-model="filterForm.costCategory"
								placeholder="请选择"
								clearable
								@change="handleFilterChange"
							>
								<el-option
									v-for="item in costCategoryOptions"
									:key="item.dictValue"
									:label="item.dictLabel"
									:value="item.dictValue"
								/>
							</el-select>
						</el-form-item>
					</el-col>

					<!-- 新增：数据来源 -->
					<el-col :span="5">
						<el-form-item label="数据来源">
							<el-select
								v-model="filterForm.dataSource"
								placeholder="请选择"
								clearable
								@change="handleFilterChange"
							>
								<el-option label="手动录入" value="手动录入" />
								<el-option label="测点获取" value="测点获取" />
							</el-select>
						</el-form-item>
					</el-col>

					<!-- 保留新增按钮 -->
				</el-row>
			</el-form>
		</el-card>

		<!-- 成本概览卡片 -->
		<!-- <el-row
			:gutter="20"
			class="mt-2"
			style="display: flex; justify-content: space-between"
		>
			<el-col :span="4" v-for="(item, index) in costSummary" :key="index">
				<el-card>
					<div class="cost-card">
						<div class="cost-type">{{ item.costCategory }}</div>
						<div class="cost-amount">¥{{ formatNumber(item.costCount) }}</div>
						<div class="cost-percentage">
							占比 {{ (item.proportion * 100).toFixed(1) }}%
						</div>
					</div>
				</el-card>
			</el-col>
		</el-row> -->

		<!-- 视图切换 -->
		<el-card class="mt-2">
			<!-- <el-radio-group
				v-model="currentView"
				size="large"
				@change="handleViewChange"
			>
				<el-radio-button label="table">表格视图</el-radio-button>
				<el-radio-button label="chart">图表视图</el-radio-button>
			</el-radio-group> -->
			<el-col>
				<el-button type="primary" icon="Plus" @click="showAddDialog = true">
					录入成本
				</el-button>
			</el-col>
			<!-- 表格视图 -->
			<div v-if="currentView === 'table'">
				<el-table
					:data="tableData"
					border
					style="width: 100%"
					class="mt-2"
					v-loading="loading"
				>
					<el-table-column
						prop="costCategory"
						label="成本类别"
						align="center"
					/>
					<el-table-column prop="costItem" label="成本项目" align="center" />
					<el-table-column prop="unitPrice" label="单价(元)" align="center">
						<template #default="{ row }">
							¥{{ row.unitPrice.toFixed(2) }}
						</template>
					</el-table-column>
					<el-table-column prop="consumption" label="消耗量" align="center" />
					<el-table-column prop="totalPrice" label="总价(元)" align="center">
						<template #default="{ row }">
							¥{{ row.totalPrice.toFixed(2) }}
						</template>
					</el-table-column>
					<el-table-column prop="dataSource" label="数据来源" align="center" />
					<el-table-column prop="inputTime" label="录入时间" align="center" />
					<el-table-column label="操作" align="center" width="150">
						<template #default="{ row }">
							<el-button type="text" @click="handleEdit(row)">编辑</el-button>
							<el-button
								type="text"
								@click="handleDelete(row)"
								style="color: #f56c6c"
								>删除</el-button
							>
						</template>
					</el-table-column>
				</el-table>

				<el-pagination
					class="mt-2"
					v-model:current-page="currentPage"
					v-model:page-size="pageSize"
					:page-sizes="[10, 20, 50]"
					layout="total, sizes, prev, pager, next"
					:total="total"
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
				/>
			</div>

			<!-- 图表视图 -->
			<div v-else class="chart-view">
				<el-row :gutter="20">
					<el-col :span="24">
						<el-card shadow="hover">
							<template #header>
								<div class="chart-title">成本构成分析</div>
							</template>
							<div class="chart-container">
								<e-charts :option="compositionOption" style="height: 400px" />
							</div>
						</el-card>
					</el-col>
					<!-- <el-col :span="12">
            <el-card shadow="hover">
              <template #header>
                <div class="chart-title">成本趋势分析</div>
              </template>
              <div class="chart-container">
                <e-charts :option="trendOption" style="height: 300px;" />
              </div>
            </el-card>
          </el-col> -->
				</el-row>
			</div>
		</el-card>

		<!-- 新增/编辑成本对话框 -->
		<el-dialog
			v-model="showAddDialog"
			:title="isEditing ? '编辑成本记录' : '新增成本录入'"
			width="600px"
			:close-on-click-modal="false"
		>
			<el-form :model="costForm" label-width="100px">
				<el-form-item label="成本类别" required>
					<el-select
						v-model="costForm.costCategory"
						placeholder="请选择成本类别"
					>
						<el-option
							v-for="item in costCategoryOptions"
							:key="item.dictValue"
							:label="item.dictLabel"
							:value="item.dictValue"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="成本项目" required>
					<el-input v-model="costForm.costItem" placeholder="请输入成本项目" />
				</el-form-item>
				<el-form-item label="单价(元)" required>
					<el-input-number
						v-model="costForm.unitPrice"
						:min="0"
						:precision="2"
						controls-position="right"
						style="width: 100%"
					/>
				</el-form-item>
				<el-form-item label="消耗量" required>
					<el-input-number
						v-model="costForm.consumption"
						:min="0"
						:precision="2"
						controls-position="right"
						style="width: 100%"
					/>
				</el-form-item>
				<el-form-item label="录入时间">
					<el-date-picker
						v-model="costForm.inputTime"
						type="datetime"
						placeholder="Select date and time"
						value-format="YYYY-MM-DD HH:mm:ss"
					/>
				</el-form-item>
				<el-form-item label="备注">
					<el-input
						v-model="costForm.remark"
						type="textarea"
						:rows="2"
						placeholder="请输入备注信息"
					/>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="showAddDialog = false">取消</el-button>
				<el-button type="primary" @click="handleSubmit">
					{{ isEditing ? "更新" : "确认" }}
				</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
	import { ref, onMounted, computed } from "vue";
	import { ElMessage, ElMessageBox } from "element-plus";
	import ECharts from "@/components/ECharts";
	import {
		getSiteList,
		getCostCategoryList,
		getCostStatistics,
		getCostDetails,
		getCostDetail,
		addCostDetail,
		updateCostDetail,
		deleteCostDetail,
	} from "@/api/prod_operate/synthesis/cost/cost_detail";

	// 替换原有的filterForm定义
	const filterForm = ref({
		siteId: "", // 保留水厂站点
		startDate: "", // 新增：开始时间
		endDate: "", // 新增：结束时间
		costCategory: "", // 新增：成本类别
		dataSource: "", // 新增：数据来源
	});

	// 站点选项
	const siteOptions = ref([]);
	// 成本类别选项
	const costCategoryOptions = ref([]);

	// 表格数据
	const tableData = ref([]);
	const loading = ref(false);
	const total = ref(0);

	// 分页控制
	const currentPage = ref(1);
	const pageSize = ref(10);

	// 视图控制
	const currentView = ref("table");

	// 成本统计数据
	const costSummary = ref([]);

	// 图表配置
	const compositionOption = ref({});
	const trendOption = ref({});

	// 新增/编辑对话框
	const showAddDialog = ref(false);
	const isEditing = ref(false);
	const costForm = ref({
		costCategory: "",
		costItem: "",
		unitPrice: 0,
		consumption: 0,
		dataSource: "手动录入",
		remark: "",
		inputTime: "",
	});

	// 初始化数据
	const initData = async () => {
		try {
			// 获取站点下拉列表
			const siteRes = await getSiteList();
			siteOptions.value = siteRes.data.map((item) => ({
				id: item.id,
				name: item.name,
			}));

			// 获取成本类别下拉列表
			const categoryRes = await getCostCategoryList();
			costCategoryOptions.value = categoryRes.data;

			// 获取成本统计数据
			await fetchCostStatistics();

			// 获取成本明细数据
			await fetchCostDetails();
		} catch (error) {
			console.error("初始化数据失败:", error);
		}
	};

	// 获取成本统计数据
	const fetchCostStatistics = async () => {
		try {
			const params = {
				siteId: filterForm.value.siteId,
				dateDimension: filterForm.value.dateDimension,
				date: filterForm.value.date,
			};
			const res = await getCostStatistics(params);
			costSummary.value = res.data;

			// 更新成本构成图表
			updateCompositionChart();
		} catch (error) {
			console.error("获取成本统计失败:", error);
		}
	};

	// 修改获取成本明细数据的参数
	const fetchCostDetails = async () => {
		try {
			loading.value = true;
			const params = {
				siteId: filterForm.value.siteId,
				startDate: filterForm.value.startDate, // 替换原date参数
				endDate: filterForm.value.endDate,
				costCategory: filterForm.value.costCategory,
				dataSource: filterForm.value.dataSource,
				pageNum: currentPage.value,
				pageSize: pageSize.value,
			};
			const res = await getCostDetails(params);
			tableData.value = res.rows;
			total.value = res.total;
		} catch (error) {
			console.error("获取成本明细失败:", error);
		} finally {
			loading.value = false;
		}
	};

	// 更新成本构成图表
	const updateCompositionChart = () => {
		compositionOption.value = {
			tooltip: {
				trigger: "item",
				formatter: "{a} <br/>{b}: ¥{c} ({d}%)",
			},
			legend: {
				orient: "vertical",
				right: 10,
				top: "center",
				data: costSummary.value.map((item) => item.costCategory),
			},
			series: [
				{
					name: "成本构成",
					type: "pie",
					radius: ["50%", "70%"],
					avoidLabelOverlap: false,
					itemStyle: {
						borderRadius: 10,
						borderColor: "#fff",
						borderWidth: 2,
					},
					label: {
						show: false,
						position: "center",
					},
					emphasis: {
						label: {
							show: true,
							fontSize: "18",
							fontWeight: "bold",
						},
					},
					labelLine: {
						show: false,
					},
					data: costSummary.value.map((item) => ({
						value: item.costCount,
						name: item.costCategory,
					})),
				},
			],
		};
	};

	// 统一筛选条件变化的处理函数（替换原有的handleSiteChange等分散方法）
	const handleFilterChange = () => {
		// 重置页码为1
		currentPage.value = 1;
		// 刷新数据
		fetchCostStatistics();
		fetchCostDetails();
	};

	// 更新趋势图表
	const updateTrendChart = () => {
		console.log(costSummary.value);

		// 这里需要根据实际接口数据更新趋势图
		trendOption.value = {
			tooltip: {
				trigger: "axis",
			},
			legend: {
				data: costSummary.value.map((item) => item.costCategory),
			},
			grid: {
				left: "3%",
				right: "4%",
				bottom: "3%",
				containLabel: true,
			},
			xAxis: {
				type: "category",
				boundaryGap: false,
				data: [
					"1月",
					"2月",
					"3月",
					"4月",
					"5月",
					"6月",
					"7月",
					"8月",
					"9月",
					"10月",
					"11月",
					"12月",
				],
			},
			yAxis: {
				type: "value",
			},
			series: costSummary.value.map((item) => ({
				name: item.costCategory,
				type: "line",
				data: Array(12)
					.fill(0)
					.map(() => Math.round(item.costCount * (0.5 + Math.random()))),
			})),
		};
	};

	// 站点变化处理
	const handleSiteChange = () => {
		refreshData();
	};

	// 日期维度变化处理
	const handleDimensionChange = () => {
		refreshData();
	};

	// 日期变化处理
	const handleDateChange = () => {
		refreshData();
	};

	// 视图变化处理
	const handleViewChange = () => {
		if (currentView.value === "chart") {
			updateTrendChart();
		}
	};

	// 分页大小变化
	const handleSizeChange = (val) => {
		pageSize.value = val;
		fetchCostDetails();
	};

	// 当前页变化
	const handleCurrentChange = (val) => {
		currentPage.value = val;
		fetchCostDetails();
	};

	// 刷新数据
	const refreshData = () => {
		currentPage.value = 1;
		fetchCostStatistics();
		fetchCostDetails();
	};

	// 格式化数字
	const formatNumber = (num) => {
		return num.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
	};

	// 编辑记录
	const handleEdit = async (row) => {
		try {
			const res = await getCostDetail(row.id);
			costForm.value = {
				...res.data,
				remark: "",
			};
			isEditing.value = true;
			showAddDialog.value = true;
		} catch (error) {
			console.error("获取成本详情失败:", error);
			ElMessage.error("获取成本详情失败");
		}
	};

	// 删除记录
	const handleDelete = (row) => {
		ElMessageBox.confirm("确定要删除这条成本记录吗?", "提示", {
			confirmButtonText: "确定",
			cancelButtonText: "取消",
			type: "warning",
		})
			.then(async () => {
				try {
					await deleteCostDetail(row.id);
					ElMessage.success("删除成功");
					refreshData();
				} catch (error) {
					console.error("删除成本记录失败:", error);
					ElMessage.error("删除失败");
				}
			})
			.catch(() => {
				// 取消删除
			});
	};

	// 提交表单
	const handleSubmit = async () => {
		if (!costForm.value.costCategory || !costForm.value.costItem) {
			ElMessage.error("请填写完整的成本信息");
			return;
		}

		try {
			const data = {
				...costForm.value,
				totalPrice: costForm.value.unitPrice * costForm.value.consumption,
			};

			if (isEditing.value) {
				await updateCostDetail(data);
				ElMessage.success("更新成功");
			} else {
				await addCostDetail(data);
				ElMessage.success("添加成功");
			}

			showAddDialog.value = false;
			refreshData();
		} catch (error) {
			console.error("提交成本记录失败:", error);
			ElMessage.error("操作失败");
		}
	};

	// 初始化
	onMounted(() => {
		initData();
	});
</script>

<style scoped>
	.app-container {
		padding: 20px;
		background-color: #f5f7fa;
	}

	.cost-card {
		text-align: center;
		padding: 15px 0;
	}

	.cost-type {
		font-size: 16px;
		color: #909399;
		margin-bottom: 10px;
	}

	.cost-amount {
		font-size: 20px;
		font-weight: bold;
		color: #303133;
		margin-bottom: 5px;
	}

	.cost-percentage {
		font-size: 14px;
		color: #67c23a;
	}

	.chart-view {
		margin-top: 20px;
	}

	.chart-container {
		height: 400px;
		width: 100%;
	}

	.chart-title {
		font-size: 16px;
		font-weight: bold;
		color: #303133;
	}
</style>
